package com.strategy.demo.factory;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.strategy.demo.INoticeStrategy;
import com.strategy.demo.annotation.NoticeType;
import com.strategy.demo.enums.NoticeTypeEnum;

/**
 * 通知策略工厂（实现类中无事务版）
 * @author francis
 */
@Component
public class NoticeStrategyFactory{

	private Map<NoticeTypeEnum, INoticeStrategy> strategyMap = new ConcurrentHashMap<>();
	
	/**
	 * Autowired 会自动注入所有的实现NoticeStrategyFactory的bean <br/>
	 * 然后获取类上NoticeType注解的值替换掉 bean初始化的名称 组成一个新的strategyMap
	 * @param strategyMap
	 */
	@Autowired
	public NoticeStrategyFactory(Map<String, INoticeStrategy> strategyMap) {
		this.strategyMap.clear();
		Set<String> strategyKeys = strategyMap.keySet();
		for (String key : strategyKeys) {
			Class<? extends INoticeStrategy> clazz = strategyMap.get(key).getClass();
			NoticeType annotation = clazz.getAnnotation(NoticeType.class);
			if (annotation != null) {
				this.strategyMap.put(annotation.value(), strategyMap.get(key));
			}
		}
	}
	
	/**
	 * 寻找对应得策略处理器
	 */
	public INoticeStrategy getHandler(NoticeTypeEnum type) {
		return strategyMap.get(type);
	}
	
}
